package com.zhanglu.fun.services.chatroom.login;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhanglu.fun.services.chatroom.bean.request.TokenRequest;
import com.zhanglu.fun.services.chatroom.client.AuthenticationClient;
import com.zhanglu.fun.tookit.jwt.AuthenticationUser;

import lombok.extern.slf4j.Slf4j;

/**
 * @description
 * @Auther zhanglu
 * @Date 2017/10/20 下午4:03
 */
@Service
@Slf4j
public class TokenService {
    @Autowired
    private AuthenticationClient authenticationClient;

    public String getToken(String username, String password) {
        return authenticationClient.getToken(username, password);
    }

    public String registerToken(HttpServletResponse httpServletResponse, TokenRequest tokenRequest) {
        String token = authenticationClient.registerToken(tokenRequest);
        log.debug("registerToken token is {}", token);
        setCookie(httpServletResponse, token);
        return token;
    }

    public String refreshToken(HttpServletResponse httpServletResponse, String token) {
        String newToken = authenticationClient.refreshToken(new TokenRequest().setToken(token));
        log.debug("registerToken token is {}", newToken);
        setCookie(httpServletResponse, newToken);
        return newToken;
    }

    public boolean deleteToken(String token) {
        return authenticationClient.deleteToken(token);
    }

    public void setCookie(HttpServletResponse httpServletResponse, String token) {
        Cookie cookie = new Cookie("user_token", token);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 12 * 14);
        httpServletResponse.addCookie(cookie);
    }
}
